package com.qfedu.yanglao20admin.sysAdmin.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qfedu.yanglao20.common.constants.CommonConstants;
import com.qfedu.yanglao20.common.exeception.CommonException;
import com.qfedu.yanglao20.entity.sysAdmin.SysRole;
import com.qfedu.yanglao20admin.sysAdmin.dao.SysRoleDao;
import com.qfedu.yanglao20admin.sysAdmin.param.SysRoleParam;
import com.qfedu.yanglao20admin.sysAdmin.service.SysRoleService;
import com.qfedu.yanglao20admin.sysAdmin.vo.SysRoleVO;
import com.qfedu.yanglao20admin.sysAdmin.vo.SysUserVO;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class SysRoleServiceImpl implements SysRoleService {

    @Resource
    private SysRoleDao sysRoleDao;

    @Override
    public Page<SysRoleVO> pageSysRoleList(SysRoleParam param) {
        // 计算偏移量
        Integer offset = (param.getPageNum() - 1) * param.getPageSize();
        param.setOffset(offset);

        //分页查询
        Page<SysRoleVO> page = new Page<>(param.getPageNum(), param.getPageSize());
        List<SysRoleVO> sysRoles = sysRoleDao.selectList(param);

        //页码
        page.setCurrent(param.getPageNum());
        //每页查询的记录数
        page.setSize(param.getPageSize());
        //总记录数
        Long aLong = sysRoleDao.selectCount(null);
        page.setTotal(aLong);
        page.setRecords(sysRoles);
        return page;
    }

    @Override
    public List<SysUserVO> selectCountRoleName(String roleName) {
        SysRole sysRole = sysRoleDao.selectByRoleName(roleName);

        if (sysRole == null) {
            throw new CommonException(CommonConstants.ERROR, "该角色名称不存在");
        }
        return sysRoleDao.selectCountRoleName(roleName);
    }

    @Override
    public SysRole selectById(Integer id) {
        return sysRoleDao.selectById(id);
    }

    @Override
    public void deleteById(Integer id) {
        sysRoleDao.deleteById(id);
    }

    @Override
    public void add(SysRole sysRole) {
        if (sysRole.getRoleName() == null || sysRole.getRoleName().isEmpty()) {
            throw new CommonException(CommonConstants.ERROR, "请填写角色名称");
        }
        SysRole sysRole1 = sysRoleDao.selectByRoleName(sysRole.getRoleName());

        if (sysRole1 != null ) {
            throw new CommonException(CommonConstants.ERROR,"该角色名称已存在");
        }
        sysRoleDao.add(sysRole);
    }

    @Override
    public void updateSysRole(SysRole sysRole) {
        if (sysRole.getRoleName() == null || sysRole.getRoleName().isEmpty()) {
            throw new CommonException(CommonConstants.ERROR, "请填写角色名称");
        }
        SysRole sysRole1 = sysRoleDao.selectByRoleName(sysRole.getRoleName());

        if (sysRole1 != null ) {
            if (!sysRole.getId().equals(sysRole1.getId())) {
                throw new CommonException(CommonConstants.ERROR,"该角色名称已存在");
            }
        }
        sysRoleDao.update(sysRole);
    }
}
